package com.example.mediaservice.websocket;

import org.springframework.stereotype.Controller;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.CopyOnWriteArraySet;

@Controller
@ServerEndpoint("/page/image")
public class SendImage {
    public static final CopyOnWriteArraySet<SendImage> sendImgSessions = new CopyOnWriteArraySet<>();
    public Session session;

    @OnOpen
    public void onOpen(Session session) throws IOException {
        System.out.println("onOpen");
        this.session = session;
        session.getBasicRemote().sendText("连接成功");
        sendImgSessions.add(this);
    }

    @OnClose
    public void onClose() throws IOException {
        System.out.println("onClose");
        sendImgSessions.remove(this);
        this.session.close();
    }

    @OnMessage
    public void onMessage(byte[] pcmData, Session session) {
    }

    @OnError
    public void onError(Session session, Throwable error) throws IOException {
        System.out.println("onError");
        error.printStackTrace();
        sendImgSessions.remove(this);
        session.close();
    }

    public void sendMessage(ByteBuffer pcmData) throws IOException {
        this.session.getBasicRemote().sendBinary(pcmData);
    }
}
